import LayerUtils from './LayerUtils'

export default class mapLayer {
  constructor(map) {
    this.LayerUtils = new LayerUtils(map)
    // 行政区域
    this.countyNames = ['顺庆区', '高坪区', '嘉陵区', '仪陇', '蓬安', '西充', '营山', '南部', '阆中市']
    //map实列
    this.map = map
    // 行政区域查询控件
    this.districtTask = null
    //Popup弹框
    this.popupDom = new SGMap.Popup({
      // 是否显示关闭按钮
      closeButton: false,
      closeOnClick: false,
      offset: {
        bottom: [-4, -36]
      },
      className: 'hightlight-popup'
    })
    //线数据
    this.lineData = []
    this.countyNameFeatures = []
    this.cityFeatures = []
    this.countyFeatures = []
    // 已选中的区县图形数据
    this.selectedFeatures = null
    // hover的区县图形数据
    this.hoverFeatures = null
    this.clearTemp()
    this.addCityLayer()
    this.addCountyLineLayer()
    this.addCountyPolygonLayer()
    this.addCountyPolygonLayer('county_polygon_highlight', { opacity: 0.3 })
    this.addCountyNameLayer()
    this.addLineData()
    this.loadPlugin()
    this.addEquipmentLayer()
    this.addEvent()
  }
  //添加市区域线图层
  addCityLayer() {
    !this.map.getLayer(`city_line`) &&
      this.map.addLayer({
        id: `city_line`,
        type: 'line',
        source: {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: []
          }
        },
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#09776f',
          'line-width': 3,
          'line-opacity': 0.7
        }
      })
  }
  //添加区县及数据图层边框线
  addCountyLineLayer(layerId = 'county_line', options = {}) {
    !this.map.getLayer(`${layerId}`) &&
      this.map.addLayer({
        id: `${layerId}`,
        type: 'line',
        source: {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: []
          }
        },
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': options.color || '#09776f',
          'line-width': 1.5,
          'line-opacity': 0.7
        }
      })
  }
  //添加区县面图层
  addCountyPolygonLayer(layerId = 'county_polygon', options = {}) {
    // 区域面
    !this.map.getLayer(`${layerId}`) &&
      this.map.addLayer({
        id: `${layerId}`,
        type: 'fill',
        source: {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: []
          }
        },
        paint: {
          'fill-color': options.color || '#09776f',
          'fill-opacity': options.opacity || 0.1
        }
      })
  }
  //添加区县名称图层
  addCountyNameLayer() {
    !this.map.getLayer(`county_name`) &&
      this.map.addLayer({
        id: `county_name`,
        type: 'symbol',
        source: {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: []
          }
        },
        layout: {
          'text-ignore-placement': false,
          'text-field': '{name}',
          'text-size': 12,
          'text-anchor': 'top',
          'text-allow-overlap': false,
          'text-offset': [0, 0],
          'text-max-width': 8,
          'text-font': ['Microsoft YaHei Regular']
        },
        paint: {
          'text-color': 'blue',
          'text-halo-color': '#FFFFFF',
          'text-halo-width': 1.5
        }
      })
  }
  //添加图标图层
  addEquipmentLayer() {
    !this.map.getLayer('icon_image') &&
      this.map.addLayer({
        id: 'icon_image',
        type: 'symbol',
        source: {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: []
          }
        },
        layout: {
          'icon-image': '{icoName}',
          // "icon-size": 0.8,
          'icon-size': {
            type: 'exponential',
            stops: [
              [9, 0.4],
              [12, 0.6],
              [16, 0.8],
              [18, 1]
            ]
          },
          // "visibility":["get","isCheck"],
          'icon-allow-overlap': true,
          'icon-ignore-placement': true,
          'text-field': '{name}',
          'text-size': {
            type: 'exponential',
            stops: [
              [8, 11],
              [14, 12]
            ]
          },
          'text-anchor': 'top',
          'text-allow-overlap': true,
          'icon-anchor': 'bottom',
          'text-offset': [0, 0.5],
          'text-max-width': 8,
          'text-font': ['Microsoft YaHei Regular']
          // : ["get", "pattern"]
        },
        paint: {
          'text-color': 'red',
          'text-halo-color': '#FFFFFF',
          'text-halo-width': 1
        }
      })
  }
  //添加数据线图层
  addLineData() {
    !this.map.getLayer(`line_data`) &&
      this.map.addLayer({
        id: `line_data`,
        type: 'line',
        source: {
          type: 'geojson',
          data: {
            type: 'FeatureCollection',
            features: []
          }
        },
        layout: {
          'line-cap': 'round',
          'line-join': 'round'
        },
        paint: {
          'line-color': '#ff1a1a',
          'line-width': 4,
          'line-opacity': 0.7
        }
      })
  }
  //思级插件获取数据
  loadPlugin() {
    return new Promise((resolve, reject) => {
      SGMap.plugin(['SGMap.DistrictTask']).then((res) => {
        this.districtTask = new SGMap.DistrictTask()
        this.search('南充市', true)
        this.countyNames.forEach((name) => {
          this.search(name)
        })
        resolve(this.districtTask)
      })
    })
  }
  search(keyword, isCity) {
    if (!this.districtTask) {
      return
    }
    this.districtTask
      .searchDistrict({
        keyword: keyword,
        levels: 'city,county',
        pageIndex: 1,
        pageSize: 20,
        extension: true,
        subdistrict: 0
      })
      .then((result) => {
        if (!result.data) return
        result = result.data
        if (!result.districts) {
          return
        }
        for (var i = 0; i < result.districts.length; i++) {
          let features = {
            type: 'Feature',
            geometry: result.districts[i].shape,
            properties: {
              name: keyword
            }
          }
          // 计算区县中心点，用于显示区县名称
          if (!isCity) {
            // 将多区域顶点放到单区域顶点，便于计算中心点
            let shape = features.geometry.coordinates
            let _shape = []
            for (let i = 0; i < shape.length; i++) {
              for (let j = 0; j < shape[i].length; j++) {
                _shape.push(shape[i][j])
              }
            }
            let polygon = turf.polygon(_shape)
            let centroid = turf.centroid(polygon)
            centroid.properties = features.properties
            this.countyNameFeatures.push(centroid)
          }

          switch (result.districts[i].level) {
            case 'city':
              this.cityFeatures.push(features)
              break
            case 'county':
              this.countyFeatures.push(features)
              break
          }
        }

        // 更新图层数据
        if (isCity && this.cityFeatures.length) {
          this.map.getSource(`county_polygon`) &&
            this.map.getSource('city_line').setData({
              type: 'FeatureCollection',
              features: this.cityFeatures
            })
        }
        if (this.countyFeatures.length) {
          this.map.getSource(`county_polygon`) &&
            this.map.getSource(`county_polygon`).setData({
              type: 'FeatureCollection',
              features: this.countyFeatures
            })
          this.map.getSource(`county_line`) &&
            this.map.getSource(`county_line`).setData({
              type: 'FeatureCollection',
              features: this.countyFeatures
            })
        }
        if (this.countyNameFeatures.length) {
          this.map.getSource(`county_name`) &&
            this.map.getSource(`county_name`).setData({
              type: 'FeatureCollection',
              features: this.countyNameFeatures
            })
        }
      })
  }
  //添加事件
  addEvent() {
    this.map.on('mousemove', this.mapMousemoveEvent.bind(this))
    this.map.on('click', this.mapClickEvent.bind(this))
  }
  //地图点击打开弹框
  mapClickEvent(e) {
    var width = 10
    var height = 20
    var features = this.map.queryRenderedFeatures(
      [
        [e.point.x - width / 2, e.point.y - height / 2],
        [e.point.x + width / 2, e.point.y + height / 2]
      ],
      { layers: ['icon_image'] }
    )
    if (features.length != 0) {
      this.popupDom && this.popupDom.remove()
      this.popupDom
        .setLngLat([features[0].geometry.coordinates[0], features[0].geometry.coordinates[1]])
        .setHTML(`<div><span>${'测试测试测试'}</span></div>`)
        .addTo(this.map)
      this.setLineData(true)
    } else {
      this.popupDom && this.popupDom.remove()
      this.setLineData(false)
    }
  }
  //渲染线数据
  setLineData(e) {
    if (e) {
      this.map.getSource(`line_data`).setData({
        type: 'FeatureCollection',
        features: this.lineData
      })
    } else {
      this.map.getSource(`line_data`).setData({
        type: 'FeatureCollection',
        features: []
      })
    }
  }
  clearTemp() {
    this.selectedFeatures = null
  }
  mapMousemoveEvent(e) {
    const features = this.selectCounty(e)
    this.hoverFeatures = features
    if (features) {
      // 如果选中的与hover的区县相同就清空hover
      if (this.selectedFeatures && this.selectedFeatures.properties.name === features.properties.name) {
        this.hoverFeatures = null
      }
    }
    this.updateHoverSelectedFeatures()
  }

  selectCounty(e) {
    let pt = [e.lngLat.lng, e.lngLat.lat]
    let point = this.map.project(pt)
    let range = this.getRange(point)
    const selected = this.map.queryRenderedFeatures(range, {
      layers: ['county_polygon']
    })
    if (selected.length) {
      const shape = this.countyFeatures.find((item) => item.properties.name === selected[0].properties.name)
      return shape
    } else {
      return null
    }
  }
  getRange(point, width = 10, height = 10) {
    return [
      [point.x - width / 2, point.y - height / 2],
      [point.x + width / 2, point.y + height / 2]
    ]
  }
  updateHoverSelectedFeatures() {
    let features = [this.hoverFeatures, this.selectedFeatures]
    this.updateHighlight(features.filter((item) => item))
  }
  updateHighlight(features = []) {
    if (!this.map) {
      return
    }
    this.map.getSource(`county_polygon_highlight`) &&
      this.map.getSource(`county_polygon_highlight`).setData({
        type: 'FeatureCollection',
        features
      })
  }
}
